package com.sz.demo.strategy;

import com.sz.demo.ShoppingCart;
import com.sz.demo.discount.DiscountStrategy;
import com.sz.demo.model.Fruit;
import java.math.BigDecimal;
import java.util.List;

/**
 * 抽象定价策略类
 * @author Lenovo
 */
public abstract class AbstractPricingStrategy implements PricingStrategy {

    @Override
    public BigDecimal calculateTotal(ShoppingCart cart) {
        BigDecimal total = calculateDiscountedSubtotal(cart);
        return applyPromotion(total);
    }

    /**
     * 计算应用商品折扣后的小计
     */
    protected BigDecimal calculateDiscountedSubtotal(ShoppingCart cart) {
        BigDecimal subtotal = BigDecimal.ZERO;
        List<Fruit> items = cart.getItems();

        for (Fruit fruit : items) {
            // 使用Product类的calculatePrice方法，已经考虑了商品自身的折扣
            DiscountStrategy discountStrategy = getDiscountStrategyFor(fruit);
            subtotal = subtotal.add(discountStrategy.applyDiscount(fruit, 1));
        }

        return subtotal;
    }

    /**
     * 获取特定水果的折扣策略
     */
    protected abstract DiscountStrategy getDiscountStrategyFor(Fruit fruit);

    /**
     * 应用促销策略
     */
    protected abstract BigDecimal applyPromotion(BigDecimal subtotal);
}
